﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MotelCores.FederatedIdentity;
using System.Runtime.Serialization.Json;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace MotelClient
{
    public partial class Motel : System.Web.UI.Page
    {
        private string realm = null;
        private string provider = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + ":" + Request.Url.Port + Request.ApplicationPath;
            if (!IsPostBack)
            {
                var loginSession = Session["IsLogin"];
                string isLoginSate = (loginSession == null || !(loginSession is string)) ? string.Empty : loginSession.ToString();
                if (isLoginSate.CompareTo("Login") != 0)
                {
                    if (!String.IsNullOrEmpty(Request.PathInfo))
                    {
                        if (Request.PathInfo.StartsWith("/requestToken"))
                            MakeRequestForToken();
                        else if (Request.PathInfo.StartsWith("/authorizeToken"))
                            HandleAuthorizeTokenResponse();
                    }
                }
                else
                {

                }
            }
        }

        /// <summary>
        /// Step 1: Get a Request Token
        /// </summary>
        private void MakeRequestForToken()
        {
            string consumerKey = null;
            string consumerSecret = null;
            string requestTokenEndpoint = null;
            string requestTokenCallback = null;
            string authorizeTokenUrl = null;

            if (Request.PathInfo == "/requestToken/google/")
            {
                consumerKey = "732818934461.apps.googleusercontent.com";
                consumerSecret = "KHEOJR9TeZ5e-el-P8o5e5CN";
                // Google requires an additional "scope" parameter that identifies one of the google applications
                //requestTokenEndpoint = "https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/userinfo.profile";
                requestTokenEndpoint = @"https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/userinfo#email";
                requestTokenCallback = GetRouteableUrlFromRelativeUrl("Default.aspx/authorizeToken/google/");
                authorizeTokenUrl = "https://www.google.com/accounts/OAuthAuthorizeToken";
            }
            else if (Request.PathInfo == "/requestToken/yahoo/")
            {
                consumerKey = "dj0yJmk9S0p2T1pjTTZmMExpJmQ9WVdrOVdXNUdkMnM0TnpZbWNHbzlPRGN6TURJMk5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PTAx";
                consumerSecret = "2124bb5df3133b8cdfe306952d1da8af6678bb1f";
                requestTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_request_token";
                requestTokenCallback = GetRouteableUrlFromRelativeUrl("Default.aspx/authorizeToken/yahoo/");
                authorizeTokenUrl = "https://api.login.yahoo.com/oauth/v2/request_auth";
            }

            if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
                throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

            // Step 1: Make the call to request a token
            var oAuthConsumer = new OAuthConsumer();
            var requestToken = oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint, realm, consumerKey, consumerSecret, requestTokenCallback);
            PersistRequestToken(requestToken);

            // Step 2: Make a the call to authorize the request token
            Response.Redirect(authorizeTokenUrl + "?oauth_token=" + requestToken.Token);
        }

        /// <summary>
        /// Step 3: Exchange the Request Token for an Access Token
        /// </summary>
        private void HandleAuthorizeTokenResponse()
        {
            string consumerKey = null;
            string consumerSecret = null;
            string accessTokenEndpoint = null;
            string token = null;
            string verifier = null;

            if (Request.PathInfo.StartsWith("/authorizeToken/google/"))
            {
                provider = "Google";
                consumerKey = "732818934461.apps.googleusercontent.com";
                consumerSecret = "KHEOJR9TeZ5e-el-P8o5e5CN";
                token = Request.QueryString["oauth_token"];
                verifier = Request.QueryString["oauth_verifier"];
                accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";
            }
            else if (Request.PathInfo.StartsWith("/authorizeToken/yahoo"))
            {
                provider = "Yahoo!";
                consumerKey = "dj0yJmk9S0p2T1pjTTZmMExpJmQ9WVdrOVdXNUdkMnM0TnpZbWNHbzlPRGN6TURJMk5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PTAx";
                consumerSecret = "2124bb5df3133b8cdfe306952d1da8af6678bb1f";
                token = Request.QueryString["oauth_token"];
                verifier = Request.QueryString["oauth_verifier"];
                accessTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_token";
            }

            if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
                throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

            // Exchange the Request Token for an Access Token
            var oAuthConsumer = new OAuthConsumer();
            var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);
            //Create Account
            TaiKhoanDTO tk = new TaiKhoanDTO();
            // Get email information Google only
            if (provider == "Google")
            {
                var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/userinfo/email", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
                //var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/oauth2/v1/userinfo", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
                //var hinhdaidien = oAuthConsumer.GetUserInfo(" https://www.googleapis.com/oauth2/v1/userinfo", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
                Session["Email"] = responseText.Split('&')[0].Split('=')[1];
                //Session["Email"] = string.Empty;
                Session["IsLogin"] = "Login";
                //tk.HinhDaiDien=
                tk.TenTaiKhoan = (string)Session["Email"];
                insertAcc(tk);
                //Response.Redirect("~/default.aspx/?text="+responseText);
                Response.Redirect("~/default.aspx");
            }
            else if (provider == "Yahoo!")
            {
                // Get user profile information Yahoo only
                string guid = accessToken.AddtionalProperties["xoauth_yahoo_guid"];
                string url = string.Format("http://social.yahooapis.com/v1/user/{0}/profile/usercard", guid);
                var responseText = oAuthConsumer.GetUserInfo(url, realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
                var email = MotelCores.Helpers.GetValueNodeFromXMLStringSource(responseText, "nickname");
                //var image = MotelCores.Helpers.GetValueNodeFromXMLStringSource(responseText, "image");
                Session["Email"] = email;
                Session["IsLogin"] = "Login";
                //tk.HinhDaiDien=
                tk.TenTaiKhoan = (string)Session["Email"];
                string text = insertAcc(tk);
                Response.Redirect("~/default.aspx");
            }

            //call api insert account
            //Session["IsLogin"] = "Login";
            //Response.Redirect("~/Default.aspx/?email=" + responseText.Split('&')[0].Split('=')[1]);
            //Response.Redirect("~/default.aspx/authenticated/?email=" + result);
            //Response.Redirect("~/Default.aspx");
        }

        private string insertAcc(TaiKhoanDTO tk)
        {
            string messages = string.Empty;

            WebRequest wr = WebRequest.Create("http://localhost:1790/motelmaps/inst_account");
            wr.Method = "POST";
            wr.ContentType = "application/json";
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TaiKhoanDTO));
                serializer.WriteObject(ms, tk);

                byte[] buffer = ms.ToArray();

                wr.ContentLength = buffer.Length;

                Stream streamRequest = wr.GetRequestStream();
                streamRequest.Write(buffer, 0, buffer.Length);
                streamRequest.Close();
            }
            WebResponse tempResponse = wr.GetResponse();
            using (Stream stream = tempResponse.GetResponseStream())
            {
                DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(string));
                string msgResponse = (string)dcs.ReadObject(stream);
                messages += msgResponse;
                stream.Close();
            }
            return messages;

        }

        void PersistRequestToken(RequestToken requestToken)
        {
            Session["RequestToken"] = requestToken;
        }

        RequestToken GetRequesttoken()
        {
            var requestToken = (RequestToken)Session["RequestToken"];
            Session.Remove("RequestToken");
            return requestToken;
        }

        string GetRouteableUrlFromRelativeUrl(string relativeUrl)
        {
            var url = HttpContext.Current.Request.Url;
            return url.Scheme + "://" + url.Host + ":" + Request.Url.Port + VirtualPathUtility.ToAbsolute("~/" + relativeUrl);
        }

        public string EmailA
        {
            get
            {
                if ((string)Session["IsLogin"] == "Login")
                {
                    string email = Session["Email"] as string;
                    //email = (email.Length > 5) ? email.Substring(0, 3)+"..": email;
                    return email;
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        protected void OpenLogin_Click(object sender, CommandEventArgs e)
        {
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Session["IsLogin"] = "Out";
        }
    }
}